//#import <stdio.h>

#import <stdio.h>
#import <stdlib.h>
#import <strings.h>
#import <sys/param.h>
#import <streams/streams.h>
#import <appkit/NXBitmapImageRep.h>
#import <appkit/Pasteboard.h>
#import <appkit/Listener.h>
#import <appkit/Speaker.h>
#import "GWCopyApp.h"
#import "ControlLoader.h"
#import "NXBitmapImageRepControl.h"
#import "Converter.h"

@implementation GWCopyApp

char *mktemp(char *name);

- run: (int)argc : (char **)argv
{
	id			bitmaps = [[[ControlLoader loadControl: "Bitmap"] alloc] init];
	id			image;
	id 			converter;
	char			*type = NULL;
	char			filename[MAXPATHLEN];
	char			*application = "GraphicsWorkshop";
	int			x;
	BOOL		messageGW = NO;
	NXStream	*myStream;
	
	if (argc == 1) {
		fprintf(stderr, "You must specify at least the file type\n");
		exit(1);
	} else {
		for (x = 1; x < argc; x++) {
			if (argv[x][0] == '-') {
				if (strlen(argv[x]) == 1) {
					strcpy(filename, "-");
				} else {
					switch (argv[x][1]) {
						case 'a':
						case 'A':
							application = argv[++x];
							break;
						case 'p':
						case 'P':
							messageGW = YES;
							break;
						case 't':
						case 'T':
							type = argv[++x];
							break;
						default:
							fprintf(stderr, "Unknown argument %s\n", argv[x]);
							exit (1);
					}
				}
			} else {
				strcpy(filename, argv[x]);
			}
		}
		
		if (!strcmp(filename, "-")) {
			if (type == NULL) {
				type = "tiff";
			}
			[bitmaps handleLink: type];
			converter = [bitmaps getCurrentConverter];
			fprintf(stderr, "Using Format: %s\n", [converter getFormatName]);
			myStream = NXOpenFile(fileno(stdin), NX_READONLY);
			image = [converter readFromStream: myStream from: bitmaps];
			if ([converter errorState]) {
				fprintf(stderr, "Converter Error: %d\n", [converter errorMessage]);
				exit(1);
			}
		} else {
			image = [bitmaps openAndReturnImage: filename];
		}
		[self copyToPBoard: image];
		[image free];
		
		if (messageGW) {
			int		msgDelivered, pasted;
			id		mySpeaker = [[Speaker alloc] init]; 
			port_t 	thePort = NXPortFromName(application, NULL);
			
			if (thePort != PORT_NULL) {
				[mySpeaker setSendPort: thePort];
				msgDelivered = [mySpeaker msgPaste: &pasted];
				if (msgDelivered != 0) {
					fprintf(stderr, "Unable to deliver paste message, Mach Error = %d\n",
					 					msgDelivered);
				}
			}
			[mySpeaker free];
		}
	}
	
	[bitmaps free];

	return self;
}

- copyToPBoard: (id)thePic
{
        id			myPboard = [Pasteboard newName: NXSelectionPboard];
        NXStream	*myStream;
        char			*data;
        int			length, maxLength;

        [myPboard declareTypes: &NXTIFFPboardType num:1 owner:self];
        myStream = NXOpenMemory(NULL, 0, NX_WRITEONLY);
        [thePic writeTIFF: myStream];
        NXGetMemoryBuffer(myStream, &data, &length, &maxLength);
        [myPboard writeType: NXTIFFPboardType data: data length: length];
        NXCloseMemory(myStream, NX_FREEBUFFER);

        return self;
}

@end
